package com.neshai.webapp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //private final Map<String, String> verificationCodes = new HashMap<>();
    private static final long EXPIRATION_TIME = 5;
    private static final long RESEND_LIMIT_TIME = 1; // 1 minute
    private final Random random = new Random();

    public String generateCode(String email) {
        String resendKey = "resend:" + email;
        String lastSentTime = stringRedisTemplate.opsForValue().get(resendKey);
        if (lastSentTime != null) {
            long currentTime = System.currentTimeMillis();
            long lastSentTimeMillis = Long.parseLong(lastSentTime);
            if (currentTime - lastSentTimeMillis < TimeUnit.MINUTES.toMillis(RESEND_LIMIT_TIME)) {
                throw new RuntimeException("You can only request a new code every minute.");
            }
        }

        String code = String.format("%06d", random.nextInt(999999));
        stringRedisTemplate.opsForValue().set(email, code, EXPIRATION_TIME, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(resendKey, String.valueOf(System.currentTimeMillis()), RESEND_LIMIT_TIME, TimeUnit.MINUTES);
        return code;
    }

    public boolean verifyCode(String email, String code) {
        String storedCode = stringRedisTemplate.opsForValue().get(email);
        return storedCode != null && storedCode.equals(code);
    }

    public void removeCode(String email) {
        stringRedisTemplate.delete(email);
    }
}